package com.github.llyb120.sxmanage;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import sun.misc.ThreadGroupUtils;

import javax.xml.ws.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Administrator
 * @Date: 2020/12/1 12:33
 */
@Configuration
public class WebSocketConfig {

    public static List<ServiceConfig.Config> services;
    public static Map<String, Boolean> online = new ConcurrentHashMap<>();
    public static Environment environment;

    @Bean
    public ServerEndpointExporter serverEndpointExporter(List<ServiceConfig.Config> services) {
        WebSocketConfig.services = services;
        init();
        return new ServerEndpointExporter();
    }

    @Autowired
    public void initStatic(
        Environment environment
    ){
        WebSocketConfig.environment = environment;
    }


    void init(){
        Set<String> handleMap = new ConcurrentHashSet();
        ThreadUtil.execute(() -> {
            while(true){
                ThreadUtil.sleep(1000);
                for (ServiceConfig.Config config : services) {
                    if(StrUtil.isBlank(config.getHealth())){
                        online.put(config.getName(), false);
                        continue;
                    }
                    if(handleMap.contains(config.getName())){
                        continue;
                    }
                    ThreadUtil.execute(() -> {
                        try{
                            handleMap.add(config.getName());//, true);
                            HttpResponse resp = HttpUtil.createGet(config.getHealth())
                                .timeout(5000)
                                .execute();
                            online.put(config.getName(), resp.getStatus() == 200);
                        } catch (Exception e){
                            online.put(config.getName(), false);
                        } finally {
                            handleMap.remove(config.getName());
                        }
                    });
                }
            }
        });
    }

}
